package com.example.blog.handler;

import com.alibaba.fastjson.JSON;
import com.example.blog.dao.pojo.User;
import com.example.blog.service.LoginService;
import com.example.blog.utils.UserThreadLocal;
import com.example.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //调用controller方法之前执行
        /**
         * 1、需要判断请求的接口路径是否为HandlerMethod方法(controller)
         * 2、token is null ？
         * 3、token not null 进行验证loginService checkToken
         * 4、认证成功即放行
         */
        if (!(handler instanceof HandlerMethod)){
            //handler可能是RequsetResourceHandler springboot程序访问静态资源默认访问类路径下的static目录查询
            return true;
        }
        String token = request.getHeader("Authorization");
        log.info("==================request start=====================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}",token);
        log.info("==================request end=====================");


        if (StringUtils.isBlank(token)){
            Result result = Result.fail(-1000, "token为空");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        User user = loginService.checkToken(token);
        if (user == null){
            Result result = Result.fail(-1000, "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //验证通过 放行
        UserThreadLocal.put(user);
        return true;
    }

//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
//    }
//
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //需要删除Thread中用完的信息 则会造成内存泄露的风险
        UserThreadLocal.remove();
    }

}
